package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kmzx.one.common.constants.Constants;
import com.kmzx.one.common.exceptions.NoSuchObjectException;
import com.kmzx.one.common.exceptions.ParameterNullException;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.PartnerAuth;
import com.kmzx.one.project.entity.UserInvite;
import com.kmzx.one.project.entity.UserRankBuy;
import com.kmzx.one.project.entity.WxUser;
import com.kmzx.one.project.mapper.PartnerMapper;
import com.kmzx.one.project.mapper.RankTabMapper;
import com.kmzx.one.project.mapper.UserInviteMapper;
import com.kmzx.one.project.mapper.UserProfitMapper;
import com.kmzx.one.project.mapper.UserRankBuyMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.mapper.WxUserMapper;
import com.kmzx.one.project.others.common.UserRankDetailInfo;
import com.kmzx.one.project.others.common.VIPRank;
import com.kmzx.one.project.others.dso.PartnerAuthDso;
import com.kmzx.one.project.others.dso.PartnerOutDso;
import com.kmzx.one.project.others.dso.UserRankDso;
import com.kmzx.one.project.others.dto.FatherInfo;
import com.kmzx.one.project.others.dto.PartnerOutInfo;
import com.kmzx.one.project.others.dto.PartnerReqInfo;
import com.kmzx.one.project.others.dto.UserCenterInfo;
import com.kmzx.one.project.others.dto.UserRankInfo;
import com.kmzx.one.project.others.dto.UserRankMoreInfo;
import com.kmzx.one.project.others.dto.UserRankOutInfo;
import com.kmzx.one.project.others.dto.UserRankUPInfo;
import com.kmzx.one.project.service.UserRanksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserRanksServiceImpl implements UserRanksService {


    @Autowired
    UserRankMapper userRankMapper;
    @Autowired
    UserRankBuyMapper userRankBuyMapper;

    @Autowired
    RankTabMapper rankTabMapper;

    @Autowired
    WxUserMapper wxUserMapper;

    @Autowired
    UserInviteMapper userInviteMapper;

    @Autowired
    PartnerMapper partnerMapper;

    @Autowired
    private UserProfitMapper userProfitMapper;

    @Autowired
    RedisTemplate<String, Object> stringObjectRedisTemplate;


    @Override
    public UserRankInfo findUserRankTabs(String userId) {
        List<UserRankDso> tabs = userRankMapper.selectAllRankTabs();
        UserRankInfo rankTabs = userRankMapper.selectUserRankTabs(userId);
        if (rankTabs != null) {
            for (int i = 0; i < tabs.size(); i++) {
                if (tabs.get(i).getRankId().equals(rankTabs.getRankId()) && i != tabs.size() - 1) {
                    rankTabs.setNextName(tabs.get(i + 1).getRankName());
                    break;
                }
            }
            ArrayList<VIPRank> ranks = new ArrayList<>();
            for (int i = 0; i < tabs.size(); i++) {
                VIPRank rank = new VIPRank();
                rank.setName(tabs.get(i).getRankName());
                rank.setMoney(tabs.get(i).getRankPay());
                rank.setRankNum(tabs.get(i).getRankNum());
                ranks.add(rank);
//                if (tabs.get(i).getRankNum() != 0 && rankTabs.getRankNo() < tabs.get(i).getRankNum()) {
//                }
            }
            rankTabs.setRankList(ranks);
            rankTabs.setUserId(userId);
            Double seaRankRate = rankTabs.getSeaRankRate();
            if (seaRankRate == null) {
                rankTabs.setSeaRankRate(1.0);
            }
            BigDecimal rankPay = rankTabs.getRankPay();
            BigDecimal growth = rankTabs.getGrowth();
            BigDecimal toBuy = rankPay.subtract(growth);
            rankTabs.setToBuy(toBuy);
            return rankTabs;
        }
        return null;
    }

    @Override
    public List<UserRankMoreInfo> findTopRankUser(String userId, Integer pageNum, Integer pageSize) {
//        UserRank rank = userRankMapper.selectUserRankByUserId(userId);
//        if (rank == null) {
//            return null;
//        }
//        RankTab rankTab = rankTabMapper.selectByPrimaryKey(rank.getRankId());
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserRankMoreInfo> topRankUser = userRankMapper.selectTopRankUser(userId);
        List<UserRankMoreInfo> result = topRankUser.getResult();
        if (result == null) {
            return Collections.emptyList();
        } else {
            return result;
        }
    }

    @Override
    public List<UserRankMoreInfo> findTopRankUserSearch(String userId, String nickName, Integer pageNum, Integer pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserRankMoreInfo> topRankUser = userRankMapper.selectTopRankUserSearch(userId, nickName);
        List<UserRankMoreInfo> result = topRankUser.getResult();
        if (result == null) {
            return Collections.emptyList();
        } else {
            return result;
        }
    }


    @Override
    public int doUserRankRelation(String fromUserId, String userId) {
        WxUser wxUser = wxUserMapper.selectById(fromUserId);
        if (wxUser == null) {
            throw new ParameterNullException("userId 为空");
        }
        WxUser toUser = wxUserMapper.selectById(userId);
        if (toUser == null) {
            throw new ParameterNullException("userId 为空");
        }

        Date date = new Date();

        List<String> has = userInviteMapper.checkUserInviteSingle(userId);
        if (CollectionUtils.isEmpty(has)) {
            UserInvite userInvite = new UserInvite();
            userInvite.setId(UUIDGenerator.generate());
            userInvite.setFromUser(fromUserId);
            userInvite.setToUser(userId);
            userInvite.setStates(0);
            userInvite.setCreateTime(date);
            userInvite.setUpdateTime(date);
            userInviteMapper.insert(userInvite);

        } else {
            if (has.contains(fromUserId)) {
                throw new ParameterNullException("该用户已是您的管家!");
            }
        }
        return 1;
    }

    @Override
    public UserRankBuy findUserRankBuy(String id) {
        UserRankBuy rankBuy = userRankBuyMapper.selectById(id);
        return rankBuy;
    }

    @Override
    public FatherInfo findUserFather(String userId) {
        FatherInfo info = new FatherInfo();
        List<String> father = userRankMapper.selectUserFather(userId);
        if (father != null && father.size() > 0) {
            info.setHas(true);
            UserRankInfo rankTabs = userRankMapper.selectUserRankTabs(father.get(0));
            info.setRankIcon(rankTabs.getRankIcon()).setRankName(rankTabs.getRankName())
                    .setRankNum(rankTabs.getRankNum()).setTopId(father.get(0))
                    .setTopNickName(rankTabs.getNickName()).setAvatar(rankTabs.getAvatar());

            int num = userInviteMapper.selectUserInviteNum(father.get(0));
            info.setChild(num);
            info.setProfit(BigDecimal.ZERO);
            info.setGrowth(rankTabs.getGrowth());
//            List<UserProfit> userProfits = userProfitMapper.selectByUserId(userId);
//            if (!CollectionUtils.isEmpty(userProfits)) {
//                BigDecimal profitMoney = userProfits.get(0).getAccountMoney();
//                info.setProfit(profitMoney);
//            }
        }
        return info;
    }

    @Override
    public UserRankOutInfo findUserRankDetailInfo(String userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserRankDetailInfo> pe = userRankMapper.selectUserRankUpInfo(userId);
        UserRankOutInfo outInfo = new UserRankOutInfo(pe.getPageNum(), pe.getPageSize(), pe.getStartRow(), pe.getEndRow(), pe.getTotal(), pe.getPages());
        List<UserRankDetailInfo> result = pe.getResult();
        outInfo.setChildren(result);
        return outInfo;
    }

    @Override
    public PartnerOutInfo findPartnerInfo(String userId) {
        PartnerOutInfo outInfo = new PartnerOutInfo();
        PartnerOutDso dso = partnerMapper.selectOnePartnerInfo();
        if (dso != null) {
            // -1,无任何审核记录
            // 0,成功,不显示
            // 1,前端,审核失败
            // 2 前段 待审核
            // 3,成功,审核成功
            outInfo.setResult(-1);
            outInfo.setAuthName(dso.getpName())
                    .setShopImg(dso.getStorePic())
                    .setLicenseImg(dso.getBusinessPic())
                    .setGroupImg(dso.getCustomerPic())
                    .setPartnerImg(dso.getpPic())
                    .setPartnerImg2(dso.getInnerPic())
                    .setSuccessImg(dso.getWinnerPic())
                    .setUserId(userId);
        }


        if (userId == null) {
            return outInfo;
        } else if (userId != null && !userId.equals("")) {

            UserCenterInfo userInfo = wxUserMapper.selectUserTopInfo(userId);

            if (userInfo == null) {
                throw new ParameterNullException("该用户不存在!");
            }

            UserRankInfo info = userRankMapper.selectUserRankTabs(userId);
            int rankNum1 = info.getRankNum();
            if (rankNum1 > 0) {
                outInfo.setShow(1);
            }
//            long version41 = 1585708507701l;
//            if (rankNum != 3) {
            List<PartnerAuthDso> partnerAuths = partnerMapper.selectPartnerAuthInfo(userId);
//                long nowStamp = System.currentTimeMillis() / 1000;
//                if (nowStamp > version41) {
//                }

            if (partnerAuths != null && partnerAuths.size() > 0) {
                // 有过验证记录
                PartnerAuthDso authDso = partnerAuths.get(0);
                int states = authDso.getStates();
                if (states == 1) {
                    Date lookTime = authDso.getLookTime();
                    Date verifyTime = authDso.getVerifyTime();
                    // 成功了,但是以前浏览过
                    if (lookTime.getTime() <= verifyTime.getTime()) {
                        outInfo.setResult(3);
                        StringBuilder stringBuilder = new StringBuilder(Constants.partnerAuthPrefix);
                        stringBuilder.append(authDso.getId());
                        stringObjectRedisTemplate.opsForValue().set(stringBuilder.toString(), stringBuilder.toString(), 15, TimeUnit.SECONDS);

                    } else {
                        // 成功了,也浏览过
                        outInfo.setResult(0);
                    }
                } else if (states == 2) {
                    // 审核失败
                    outInfo.setResult(1).setReason(authDso.getReason());
                    outInfo.setOldContact(authDso.getPartnerName());
                    outInfo.setOldCompany(authDso.getCompany());
                    outInfo.setOldShopImg(authDso.getStorePic());
                    outInfo.setOldLicenseImg(authDso.getBusinessPic());
                    outInfo.setOldGroupImg(authDso.getCustomerPic());
                    outInfo.setOldPhone(authDso.getPhone());
                } else {
                    // 待审核
                    outInfo.setResult(2);
                }
            } else {
                // 没有记录,说明以前的老用户
                int rankNum = rankNum1;
                if (rankNum == 3) {
                    outInfo.setResult(0);
                }
            }
//            }
        }
        return outInfo;
    }

    @Override
    public PartnerReqInfo partnerDoAuth(PartnerReqInfo req) {
        String userId = req.getUserId();
        WxUser wxUser = wxUserMapper.selectById(userId);
        if (wxUser == null) {
            throw new NoSuchObjectException("用户不存在!");
        }
        UserRankInfo info = userRankMapper.selectUserRankTabs(userId);
        int rankNum = info.getRankNum();
        if (rankNum == 3) {
            List<PartnerAuthDso> partnerAuths = partnerMapper.selectPartnerAuthInfo(userId);
            if (partnerAuths != null && partnerAuths.size() > 0) {
                int states = partnerAuths.get(0).getStates();
                if (states == 2) {
                    throw new ParameterNullException("您已经认证过,请勿重复提交!");
                }
            }
        }

        Date date = new Date();
        PartnerAuth auth = new PartnerAuth();
        auth.setId(UUIDGenerator.generate())
                .setApplyTime(date).setLookTime(date)
                .setStates(0)
                .setUserId(req.getUserId())
                .setPartnerType(req.getPartnerType())
                .setPhone(req.getPhone())
                .setPartnerName(req.getContact())
                .setCompany(req.getCompany())
                .setBusinessPic(req.getLicenseImg())
                .setStorePic(req.getShopImg())
                .setCustomerPic(req.getGroupImg());
        logger.info("顶级VIP认证,提交审核记录,{}", auth);
        partnerMapper.insertPartnerAuth(auth);
        logger.info("顶级VIP认证,提交审核记录,OK");
        req = null;
        return req;
    }

    @Override
    public UserRankUPInfo findUserRankUp(String userId) {
        UserRankUPInfo rank = userRankMapper.selectUserRankUpHistory(userId);
        if (rank != null) {
            rank.setHas(true);
        } else {
            UserRankUPInfo info = new UserRankUPInfo();
            return info;
        }
        return rank;
    }

    @Override
    public void readRankUpInfo(String userId) {
        userRankMapper.updateUserRankHistorySend(userId, 1);
    }
}
